import type { CommitStateFunction, IntentionData, ResultData, UserInfo } from '/@/types';
import {
  ACCESS_TOKEN,
  LOGIN_STATUS,
  NODE_ENV,
  USER_INFO,
  PROJECT_SETTING,
  SCOPE_NUMBER,
  MY_INTENTION,
} from '/@/utils/constants';
import { removeStorage, saveCookie, saveStorage } from '/@/utils/cache';
import * as types from '../mutationTypes';
import { ProjectConfig } from '../../types/config';
import { getAccessToken } from '../../api/api';
import { StartDate } from '../../hooks/useStartDate';

/**
 * 登录态
 * /@param commit
 * /@param state
 * /@param loginStatus
 */
export function setLoginStatus({ commit, state }: CommitStateFunction, loginStatus: number): void {
  if ((loginStatus === 0 || loginStatus === 1) && NODE_ENV === 'production') {
    removeStorage(ACCESS_TOKEN);
    removeStorage(USER_INFO);
  }
  commit(
    types.SET_LOGIN_STATUS,
    // String(loginStatus)
    saveCookie(LOGIN_STATUS, String(loginStatus), { expires: 7 })
  );
}

/**
 * 用户信息
 * /@param commit
 * /@param state
 * /@param userInfo
 */
export function setUserInfo({ commit, state }: CommitStateFunction, userInfo: UserInfo): void {
  commit(types.SET_USER_INFO, saveStorage(USER_INFO, userInfo));
}

export async function getUserInfo(
  { commit }: CommitStateFunction,
  params: { code: string; testAuth?: number }
) {
  const { code, testAuth } = params;
  const { token, user } = (await getAccessToken(code, testAuth)) as ResultData;
  commit(types.SET_USER_INFO, saveStorage(USER_INFO, user));
  commit(types.SET_ACCESS_TOKEN, saveStorage(ACCESS_TOKEN, token));
}

export function setCode({ commit, state }: CommitStateFunction, code: string): void {
  commit(types.SET_CODE, code);
}

export function setMyIntention({ commit, state }: CommitStateFunction, myIntention: string): void {
  commit(types.MY_INTENTION, saveStorage(MY_INTENTION, myIntention));
}

/**
 * token
 * /@param commit
 * /@param state
 * /@param accessToken
 */
export function setAccessToken(
  { commit, state }: CommitStateFunction,
  accessToken: string | undefined
): void {
  commit(types.SET_ACCESS_TOKEN, saveStorage(ACCESS_TOKEN, accessToken));
}

/**
 * projectSetting
 */

export function setProjectSetting(
  { commit, state }: CommitStateFunction,
  projectSetting: Partial<ProjectConfig>
): void {
  projectSetting = Object.assign({}, state.projectSetting, projectSetting) as ProjectConfig;
  commit(types.SET_PROJECT_SETTING, saveStorage(PROJECT_SETTING, projectSetting));
}

export function setScopeNumber({ commit, state }: CommitStateFunction, scopeNumber: number): void {
  commit(types.SET_SCOPE_NUMBER, saveCookie(SCOPE_NUMBER, String(scopeNumber), { expires: 7 }));
}

export function setStartDate({ commit, state }: CommitStateFunction, startDate: StartDate): void {
  commit(types.SET_START_DATE, startDate);
}

export function setIntention(
  { commit, state }: CommitStateFunction,
  intention: IntentionData
): void {
  commit(types.SET_INTENTION, intention);
}
